package com.outside.landingpage.util;


import org.apache.log4j.*;
import org.springframework.util.StringUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class LogTool {
	private static ConcurrentMap<String, Logger> deviceLoggers = new ConcurrentHashMap<String,Logger>();
	
	public static Logger getLog(String gid) {
		return createLog(gid, "30MB", 20);
	}

	public static Logger createLog(String gid, String fileSize, int backupIndex){
		if(StringUtils.isEmpty(fileSize))
			fileSize = "30MB";
		
		if(backupIndex == 0)
			backupIndex = 20;
		
		if(null != deviceLoggers.get(gid)){
			return deviceLoggers.get(gid);
		}else{
	        PropertyConfigurator.configureAndWatch("/log4j.properties");  
	        Logger logger = Logger.getLogger(gid);
	        logger.removeAllAppenders();
	        logger.setAdditivity(false);
	        logger.setLevel(Level.INFO);
	        
	        RollingFileAppender fileAppender=new RollingFileAppender();
	        fileAppender.setFile("/opt/server/outside-server/logs/" + gid + ".log");
//	        fileAppender.setFile("logs/common/" + gid + ".log");
	        fileAppender.setLayout(new PatternLayout("%p %d %t - %m%n"));
	        fileAppender.setAppend(true);
	        fileAppender.activateOptions();
	        fileAppender.setMaxFileSize(fileSize);
	        fileAppender.setMaxBackupIndex(backupIndex);
	        fileAppender.setBufferSize(1024*64);
	        logger.addAppender(fileAppender);
	        
	        deviceLoggers.put(gid, logger);
	        return logger;
		}
	}
	
	/**
	 * 
	 * @param gid 文件名
	 * @param fileSize 文件大小
	 * @param backupIndex 备份数量
	 * @return
	 */
	public static Logger getLog(String gid,String fileSize, int backupIndex){
		return createLog(gid,fileSize,backupIndex);
	}
	
}
